﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using Business;

namespace OgrIsleri.DashBoard.Modul.Akademisyenler
{
    public partial class EkleGuncelle : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack) return;

            if (Request.QueryString["Sil"] != null)
                Sil();

            SehirDoldur();

            if (Request.QueryString["Guncelle"] != null)
                Guncelle();
            
        }
        private void SehirDoldur()
        {
            using (DbEntities db = new DbEntities())
            {
                var data = db.tblSehirlers.OrderBy(o => o.SehirAdi).ToList();
                DpSehir.DataSource = data;
                DpSehir.DataTextField = "SehirAdi";
                DpSehir.DataValueField = "SehirID";
                DpSehir.DataBind();
            }
        }
        private void IlceDoldur(int SehirID)
        {
            using (DbEntities db = new DbEntities())
            {
                var data = db.tblIlcelers.Where(o=> o.SehirID == SehirID).OrderBy(o => o.IlceAdi).ToList();
                DpIlce.DataSource = data;
                DpIlce.DataTextField = "IlceAdi";
                DpIlce.DataValueField = "IlceID";
                DpIlce.DataBind();
            }
        }

        private void Guncelle()
        {
            using (DbEntities db = new DbEntities())
            {
                Guid userID = new Guid(Request.QueryString["Guncelle"]);
                var data = db.tblAkademisyenDetaylaris.Where(o => o.UserId == userID).SingleOrDefault();
                txtAdSoyad.Text = data.AdSoyad;
                txtDogumTarihi.Text = ((DateTime)(data.DogumTarihi)).ToShortDateString();
                DpCinsiyet.ClearSelection();
                DpCinsiyet.Items.FindByValue(data.Cinsiyet.ToString()).Selected = true;
                txtCepTel.Text = data.CepTel;
                txtSabitTel.Text = data.SabitTel;
                DpSehir.ClearSelection();
                DpSehir.Items.FindByValue(data.tblIlceler.tblSehirler.SehirID.ToString()).Selected = true;
                IlceDoldur(data.tblIlceler.SehirID);
                DpIlce.ClearSelection();
                DpIlce.Items.FindByValue(data.IlceID.ToString()).Selected = true;
                txtAdres.Text = data.Adres;
                txtKullaniciAdi.ReadOnly = true;
                txtKullaniciAdi.Text = data.aspnet_Users.UserName.ToString();
                txtMail.Text = data.aspnet_Users.aspnet_Membership.Email;
                Valid2.Enabled = false;
                
                BtnKaydet.Text = "Düzenle";
            }
        }

        private void Sil()
        {
            using (DbEntities db = new DbEntities())
            { 
                Guid userID = new Guid(Request.QueryString["Sil"]);
                var data = db.tblAkademisyenDetaylaris.Where(o => o.UserId == userID).SingleOrDefault();
                Membership.DeleteUser(data.aspnet_Users.UserName, deleteAllRelatedData: true);
                
            }
            Response.Redirect("Liste.aspx");
        }
        
        protected void BtnKaydet_Click(object sender, EventArgs e)
        {
            using (DbEntities db = new DbEntities())
            {
                if (Request.QueryString["Guncelle"] != null)
                {
                    MembershipUser Kullanici = Membership.GetUser(txtKullaniciAdi.Text);
                    
                    
                    Guid userID = new Guid(Request.QueryString["Guncelle"]);
                    var data = db.tblAkademisyenDetaylaris.Where(o => o.UserId == userID).SingleOrDefault();
                    data.AdSoyad = txtAdSoyad.Text;
                    data.DogumTarihi = !string.IsNullOrWhiteSpace(txtDogumTarihi.Text) ? DateTime.Parse(txtDogumTarihi.Text) : DateTime.Now;
                    data.Cinsiyet = Convert.ToInt32(DpCinsiyet.SelectedValue);
                    data.CepTel = txtCepTel.Text;
                    data.SabitTel = txtSabitTel.Text;
                    data.IlceID = Convert.ToInt32(DpIlce.SelectedValue);
                    data.Adres = txtAdres.Text;
                    db.SaveChanges();

                    var sorgu = db.aspnet_Membership.Where(o => o.UserId != (Guid)Kullanici.ProviderUserKey && o.Email == txtMail.Text).ToList();
           
                    if (sorgu.Count<=0)
                    {
                       
                        Kullanici.Email = txtMail.Text;
                        Membership.UpdateUser(Kullanici);
                    }
                    else
                    {
                        ClientScript.RegisterStartupScript(this.GetType(), "Hata", "alert('E-posta kullanımda')", true);
                        return;
                    }

                    if (!string.IsNullOrWhiteSpace(txtSifre.Text))
                    {
                        if (txtSifre.Text.Equals(txtSifreOnay.Text))
                        {
                            string EskiSifre = Kullanici.ResetPassword();
                            Kullanici.ChangePassword(EskiSifre, txtSifre.Text);
                            Response.Redirect("Liste.aspx");
                        }
                        else
                        {
                            ClientScript.RegisterStartupScript(this.GetType(), "Hata", "alert('Şifreler uyumlu değil')", true);
                        }
                    }
                    else
                    {
                        Response.Redirect("Liste.aspx");
                    }
                    
                    
                    
                }
                else
                {
                    MembershipCreateStatus status;
                    Membership.CreateUser(txtKullaniciAdi.Text, txtSifre.Text, txtMail.Text, null, null, true, out status);
                    if (status == MembershipCreateStatus.DuplicateEmail)
                    {
                        ClientScript.RegisterStartupScript(this.GetType(), "Hata", "alert('Bu e-posta adresi kullanımdadır')", true);
                    }
                    else if (status == MembershipCreateStatus.DuplicateUserName)
                    {
                        ClientScript.RegisterStartupScript(this.GetType(), "Hata", "alert('Bu kullanıcı adı kullanımdadır')", true);
                    }
                    else if (status == MembershipCreateStatus.InvalidUserName)
                    {
                        ClientScript.RegisterStartupScript(this.GetType(), "Hata", "alert('Lütfen geçerli bir kullanıcı adı yazınız')", true);
                    }
                    else if (status == MembershipCreateStatus.Success)
                    {
                        MembershipUser kullanici = Membership.GetUser(txtKullaniciAdi.Text);
                        Roles.AddUserToRole(txtKullaniciAdi.Text, "Akademisyen");

                            var data = new tblAkademisyenDetaylari();
                            data.Adres = txtAdres.Text;
                            data.AdSoyad = txtAdSoyad.Text;
                            data.CepTel = txtCepTel.Text;
                            data.Cinsiyet = Convert.ToInt32(DpCinsiyet.SelectedValue);
                            data.DogumTarihi = !string.IsNullOrWhiteSpace(txtDogumTarihi.Text) ? DateTime.Parse(txtDogumTarihi.Text) : DateTime.Now;
                            data.IlceID = Convert.ToInt32(DpIlce.SelectedValue);
                            data.SabitTel = txtSabitTel.Text;
                            data.UserId = (Guid)kullanici.ProviderUserKey;
                            db.tblAkademisyenDetaylaris.Add(data);
                            db.SaveChanges();
                            Response.Redirect("Liste.aspx");
                    }
                }
            }
            
            
        }

        protected void DpSehir_SelectedIndexChanged(object sender, EventArgs e)
        {
            DpIlce.Items.Clear();
            IlceDoldur(Convert.ToInt32(DpSehir.SelectedValue));
            DpIlce.Items.Add(new ListItem() { Text = "İlçe seçiniz", Value = "0",Selected = true });
        }
    }
}